import { parse } from '@vue/compiler-sfc';

//允许的路径
const allow_path = [
	'App.vue',
	'components/',
	'pages/',
];

let data_1 = {
	'flex'					: 'display:flex;',
	'align'					: 'align-items:center;',
	'justify'				: 'justify-content:center;',

	'text-left'				: 'text-align:left;',
	'text-center'			: 'text-align:center;',
	'text-right'			: 'text-align:right;',

	//字体加粗
	'bold'					: 'font-weight:bold;',

	'flex-row'				: 'display:flex;flex-direction:row;',
	'flex-col'				: 'display:flex;flex-direction:column;',
	'flex-row-reverse'		: 'display:flex;flex-direction:row-reverse;',
	'flex-col-reverse'		: 'display:flex;flex-direction:column-reverse;',

	'absolute'				: 'position: absolute;',
	'relative'				: 'position: relative;',
	'fixed'					: 'position: fixed;',

	'border-box'			: 'box-sizing: border-box;',
	'overflow-hidden'		: 'overflow: hidden;',
	'overflow-auto'			: 'overflow: auto;',

	//单行超出省略号
	'ellipsis'				: 'text-overflow:ellipsis;white-space:nowrap;overflow:hidden;',

	'ios'					: 'height:env(safe-area-inset-bottom);',
};

function classToStyle(str){
	let style = '';
	
	str.split(/\s+/).forEach(className => {
		if(typeof data_1[className] !== 'undefined'){
			style += data_1[className];
		}else{
			let res = /^([a-zA-Z_-]+)(\d+)$/.exec(className)

			if(res){
				switch (res[1]) {
					case 'h': style += `height: ${res[2]}rpx;`; break;
					case 'w': style += `width: ${res[2]}rpx;`; break;

					case 'left': style += `left: ${res[2]}rpx;`; break;
					case 'top': style += `top: ${res[2]}rpx;`; break;
					case 'right': style += `right: ${res[2]}rpx;`; break;
					case 'bottom': style += `bottom: ${res[2]}rpx;`; break;

					case 'm': style += `margin: ${res[2]}rpx;`; break;
					case 'mt': style += `margin-top: ${res[2]}rpx;`; break;
					case 'mb': style += `margin-bottom: ${res[2]}rpx;`; break;
					case 'ml': style += `margin-left: ${res[2]}rpx;`; break;
					case 'mr': style += `margin-right: ${res[2]}rpx;`; break;
					case 'mlr': style += `margin-left: ${res[2]}rpx;margin-right: ${res[2]}rpx;`; break;
					case 'mtb': style += `margin-top: ${res[2]}rpx;margin-bottom: ${res[2]}rpx;`; break;

					case 'p': style += `padding: ${res[2]}rpx;`; break;
					case 'pt': style += `padding-top: ${res[2]}rpx;`; break;
					case 'pb': style += `padding-bottom: ${res[2]}rpx;`; break;
					case 'pl': style += `padding-left: ${res[2]}rpx;`; break;
					case 'pr': style += `padding-right: ${res[2]}rpx;`; break;
					case 'plr': style += `padding-left: ${res[2]}rpx;padding-right: ${res[2]}rpx;`; break;
					case 'ptb': style += `padding-top: ${res[2]}rpx;padding-bottom: ${res[2]}rpx;`; break;

					case 'hh': style += `height: ${res[2]}%;`; break;
					case 'ww': style += `width: ${res[2]}%;`; break;
					case 'index': style += `z-index: ${res[2]};`; break;
					case 'radius': style += `border-radius: ${res[2]}rpx;`; break;

					case 'font': style += `font-size: ${res[2]}rpx;`; break;
					case 'lh': style += `line-height: ${res[2]}rpx;`; break;

					case 'opacity': style += `opacity: ${res[2] / 100};`; break;

					case 'show': style += `position: absolute;top:0;left:0;width:100%;height:100%;z-index: ${res[2]};`; break;

					case 'flex': style += `flex: ${res[2]};`; break;
					
					case 'wh': style += `width: ${res[2]}rpx;height: ${res[2]}rpx;`; break;
				}

			}
			
			let res2 = /^([a-zA-Z_-]+)#([0-9a-fA-F]{6}|[0-9a-fA-F]{3})$/.exec(className)
			if(res2){
				switch (res2[1]) {
					case 'bg': 
						style += `background-color: #${res2[2]};`;
					break;
					case 'color': 
						style += `color: #${res2[2]};`;
					break;
				}

			}
		}
	});

	return style;
}

var str_attr = function(str){
    var ma = /<([^>\s]+)([^>]*?)(\/)?>/g;
    var result;
    var r = [];
    var index = 0;
    while((result = ma.exec(str)) !== null){
        r.push([str.substr(index,result.index - index),...result]);
        index = ma.lastIndex;
    }
    r.push([str.substr(index),'']);
    return r;
}

var str_obj = function(str){
    var ma = /(\S+)=(["'])?((?:.(?!["']?\s+(?:\S+)=|[>"']))+.)\2?/g;
    var result;
    var r = [];
    var index = 0;
    while((result = ma.exec(str)) !== null){
        r.push([str.substr(index,result.index - index),...result]);
        index = ma.lastIndex;
    }
    r.push([str.substr(index),'']);
    return r;
}

export default function extractTemplateClassesPlugin() {
	return {
		name: 'xi_class',
		transform(src, id) {
			if (!id.endsWith('.vue')) return;

			// 检查路径是否在允许的路径中
			if (!allow_path.some(path => id.substr(__dirname.length + 1).startsWith(path))) return;

			// 解析 .vue 文件
			const { descriptor } = parse(src);

			// 检查是否有 template
			if (descriptor.template) {
				const templateContent = descriptor.template.content;

				let is_set = false

				let template = str_attr(templateContent);

				let body = '';
				for(let v of template){
					body += v[0];

					if(v[1]){
						let obj = {};
						let attrRegex = str_obj(v[3])
						
						for(let a of attrRegex){
							if(a[1]){
								obj[a[2].toLowerCase()] = a[4];
							}
						}

						if(obj.class){
							let style = classToStyle(obj.class);

							if(style){
								is_set = true;

								if (obj.style) {
									style = style + obj.style;

									let v3 = '';
									for(let a2 of attrRegex){
										v3 += a2[0];
										if(a2[1]){
											if(a2[2].toLowerCase() === 'style'){
												v3 += a2[2] + '=' + a2[3] + style + a2[3]
											}else{
												v3 += a2[1];
											}
										}
									}
									body += '<' + v[2] + v3 + (v[4] || '') + '>';
								}else{
									body += '<' + v[2] + v[3] + ' style="' + style + '"' + (v[4] || '') + '>';
								}
							}else{
								body += v[1]
							}
						}else{
							body += v[1]
						}
					}
				}

				if(is_set){
					return {
						code: src.split(descriptor.template.content).join(body),
						map: null,
					};
				}
			}
		},
	};
}